package TCPUDP;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Server {

    public static void main(String[] args) throws IOException {

        ServerSocket ss = new ServerSocket(10000);

        ThreadPoolExecutor tpe = new ThreadPoolExecutor(3,
                10,
                1,
                TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        while (true) {
            Socket socket = ss.accept();
            newThread n = new newThread(socket);
        //    new Thread(n).start();
            tpe.submit(n);
        }

    }
}

class newThread implements Runnable{

    private Socket socket;
    public newThread(Socket socket) {
        this.socket=socket;
    }
    BufferedOutputStream bos;
    @Override
    public void run() {

        //网络中的IO流

        try {
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
            //本地的数据。
            bos = new BufferedOutputStream(new FileOutputStream("F:\\"+ UUID.randomUUID().toString()+".jpg"));

            int b;

            while((b=bis.read())!=-1){
                bos.write(b);
            }

            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write("上传成功");
            bw.newLine();
            bw.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                 if(bos!=null) {
                     bos.close();
                 }
                 if(socket!=null) {
                     socket.close();
                 }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
